package cn.iocoder.yudao.module.erp.controller.admin.finance.bankstatement;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.erp.controller.admin.finance.bankstatement.vo.BankStatementPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.finance.bankstatement.vo.BankStatementRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.finance.bankstatement.vo.BankStatementSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.finance.bankstatementitem.vo.BankStatementItemPageReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.bankstatement.BankStatementDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.finance.bankstatementitem.BankStatementItemDO;
import cn.iocoder.yudao.module.erp.service.finance.bankstatement.BankStatementService;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 银行流水")
@RestController
@RequestMapping("/erp/bank-statement")
@Validated
public class BankStatementController {

    @Resource
    private BankStatementService bankStatementService;

    @PostMapping("/create")
    @Operation(summary = "创建银行流水")
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:create')")
    public CommonResult<String> createBankStatement(@Valid @RequestBody BankStatementSaveReqVO createReqVO) {
        return success(bankStatementService.createBankStatement(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新银行流水")
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:update')")
    public CommonResult<Boolean> updateBankStatement(@Valid @RequestBody BankStatementSaveReqVO updateReqVO) {
        bankStatementService.updateBankStatement(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除银行流水")
    @Parameter(name = "id", description = "编号", required = true)
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:delete')")
    public CommonResult<Boolean> deleteBankStatement(@RequestParam("id") String id) {
        bankStatementService.deleteBankStatement(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得银行流水")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:query')")
    public CommonResult<BankStatementRespVO> getBankStatement(@RequestParam("id") String id) {
        BankStatementDO bankStatement = bankStatementService.getBankStatement(id);
        return success(BeanUtils.toBean(bankStatement, BankStatementRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得银行流水分页")
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:query')")
    public CommonResult<PageResult<BankStatementRespVO>> getBankStatementPage(@Valid BankStatementPageReqVO pageReqVO) {
        PageResult<BankStatementDO> pageResult = bankStatementService.getBankStatementPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, BankStatementRespVO.class));
    }

    @GetMapping("/getBankAmountTotal")
    @Operation(summary = "银行流水统计金额")
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:query')")
    public CommonResult<BankStatementDO> getBankAmountTotal(@Valid BankStatementPageReqVO pageReqVO) {
        BankStatementDO bankStatementDO = bankStatementService.getBankAmountTotal(pageReqVO);
        return success(bankStatementDO);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出银行流水 Excel")
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportBankStatementExcel(@Valid BankStatementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
//        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<BankStatementDO> list = bankStatementService.getBankStatementPage(pageReqVO).getList();
        // 对数据进行字段处理
        List<BankStatementRespVO> processedList = list.stream().map(bankDO -> {
            BankStatementRespVO respVO = BeanUtils.toBean(bankDO, BankStatementRespVO.class);
            // 格式化创建时间
            if (bankDO.getCreateTime() != null) {
                respVO.setCreateTimeFormatted(bankDO.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            Integer currencyType = bankDO.getCurrencyType();
            if (currencyType != null) {
                if(currencyType == 1){
                    respVO.setCurrencyTypeFormatted("人民币");
                }else if(currencyType == 2){
                    respVO.setCurrencyTypeFormatted("美元");
                }else if(currencyType == 3){
                    respVO.setCurrencyTypeFormatted("坚戈");
                }else if(currencyType == 4){
                    respVO.setCurrencyTypeFormatted("卢布");
                }else {}
            }
            return respVO;
        }).collect(Collectors.toList());

        // 统计值
        BankStatementDO bankStatementDO = bankStatementService.getBankAmountTotal(pageReqVO);
        BankStatementRespVO respVO = new BankStatementRespVO();
        respVO.setId("合计");
        respVO.setDayPayment(bankStatementDO.getDayPaymentRmbSum());
        respVO.setDailyExpenses(bankStatementDO.getDailyExpensesRmbSum());
        respVO.setDailyBalance(bankStatementDO.getDailyBalanceRmbSum());
        processedList.add(respVO);
        // 导出 Excel
        ExcelUtils.write(response, "银行流水.xls", "数据", BankStatementRespVO.class,processedList);
    }

    // ==================== 子表（银行流水明细） ====================
    @GetMapping("/bank-statement-item/list-by-card-id")
    @Operation(summary = "获得银行流水明细列表")
    @Parameter(name = "cardId", description = "卡号")
    // @PreAuthorize("@ss.hasPermission('erp:bank-statement:query')")
    public CommonResult<PageResult<BankStatementItemDO>> getBankStatementItemListByCardId(@Valid BankStatementItemPageReqVO pageReqVO) {
        PageResult<BankStatementItemDO> result = bankStatementService.getBankStatementItemListByCardId(pageReqVO);
        return success(result);
    }

}